<template>
  <div class="announcement-system" v-loading="loading">
    <!-- 工具栏 -->
    <div class="announcement-toolbar">
      <div class="toolbar-left">
        <h3 class="announcement-title">{{ $t('project.announcements') }}</h3>
        <div class="announcement-filters">
          <!-- 项目选择 -->
          <el-select 
            v-model="selectedProjectId" 
            :placeholder="$t('project.selectProject')"
            class="project-select"
            @change="handleProjectChange"
          >
            <el-option
              v-for="project in projects"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
          
          <!-- 时间筛选 -->
          <el-select 
            v-model="timeFilter" 
            :placeholder="$t('project.allTime')"
            class="time-select"
            @change="handleTimeFilterChange"
          >
            <el-option
              v-for="filter in timeFilterOptions"
              :key="filter.value"
              :label="filter.label"
              :value="filter.value"
            />
          </el-select>
        </div>
      </div>
      
      <div class="toolbar-right">
        <el-input
          v-model="searchKeyword"
          :placeholder="$t('project.searchAnnouncements')"
          :prefix-icon="Search"
          class="search-input"
          @input="handleSearch"
          clearable
        />
        <el-button 
          v-if="canManage && selectedProjectId"
          type="primary" 
          :icon="Plus"
          @click="showCreateDialog = true"
        >
          {{ $t('project.createAnnouncement') }}
        </el-button>
        <el-button :icon="Refresh" @click="fetchAnnouncements">
          {{ $t('common.refresh') }}
        </el-button>
      </div>
    </div>

    <!-- 公告统计卡片 -->
    <div class="announcement-stats" v-if="selectedProjectId && announcementStats">
      <el-row :gutter="16">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">{{ announcementStats.totalAnnouncements }}</div>
              <div class="stat-label">{{ $t('project.totalAnnouncements') }}</div>
            </div>
            <el-icon class="stat-icon total"><Document /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card pinned">
            <div class="stat-content">
              <div class="stat-value">{{ announcementStats.pinnedAnnouncements }}</div>
              <div class="stat-label">{{ $t('project.pinnedAnnouncements') }}</div>
            </div>
            <el-icon class="stat-icon"><Top /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card today">
            <div class="stat-content">
              <div class="stat-value">{{ announcementStats.todayAnnouncements }}</div>
              <div class="stat-label">{{ $t('project.todayAnnouncements') }}</div>
            </div>
            <el-icon class="stat-icon"><Calendar /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card week">
            <div class="stat-content">
              <div class="stat-value">{{ announcementStats.weekAnnouncements }}</div>
              <div class="stat-label">{{ $t('project.weekAnnouncements') }}</div>
            </div>
            <el-icon class="stat-icon"><View /></el-icon>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 公告列表 -->
    <div class="announcement-list-container">
      <el-card v-if="!selectedProjectId" class="empty-state">
        <el-empty 
          :description="$t('project.selectProjectFirst')" 
          :image-size="120"
        >
          <template #image>
            <el-icon size="120"><FolderOpened /></el-icon>
          </template>
        </el-empty>
      </el-card>

      <div v-else-if="announcements.length === 0" class="empty-announcements">
        <el-empty 
          :description="$t('project.noAnnouncements')" 
          :image-size="100"
        >
          <el-button 
            v-if="canManage"
            type="primary" 
            @click="showCreateDialog = true"
          >
            {{ $t('project.createFirstAnnouncement') }}
          </el-button>
        </el-empty>
      </div>

      <div v-else class="announcement-list">
        <!-- 置顶公告 -->
        <div class="pinned-announcements" v-if="pinnedAnnouncements.length > 0">
          <div class="section-title">
            <el-icon><Top /></el-icon>
            <span>{{ $t('project.pinnedAnnouncements') }}</span>
          </div>
          <AnnouncementCard
            v-for="announcement in pinnedAnnouncements"
            :key="announcement.id"
            :announcement="announcement"
            :can-manage="canManage"
            :team-members="teamMembers"
            @edit="handleEditAnnouncement"
            @delete="handleDeleteAnnouncement"
            @pin="handlePinAnnouncement"
            @unpin="handleUnpinAnnouncement"
          />
        </div>

        <!-- 普通公告 -->
        <div class="regular-announcements">
          <div class="section-title" v-if="pinnedAnnouncements.length > 0">
            <el-icon><List /></el-icon>
            <span>{{ $t('project.regularAnnouncements') }}</span>
          </div>
          <AnnouncementCard
            v-for="announcement in regularAnnouncements"
            :key="announcement.id"
            :announcement="announcement"
            :can-manage="canManage"
            :team-members="teamMembers"
            @edit="handleEditAnnouncement"
            @delete="handleDeleteAnnouncement"
            @pin="handlePinAnnouncement"
            @unpin="handleUnpinAnnouncement"
          />
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container" v-if="regularAnnouncements.length > 0">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 创建公告对话框 -->
    <CreateAnnouncementDialog
      v-model="showCreateDialog"
      :project-id="selectedProjectId"
      @success="handleCreateSuccess"
    />

    <!-- 编辑公告对话框 -->
    <EditAnnouncementDialog
      v-model="showEditDialog"
      :announcement="selectedAnnouncement"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Refresh,
  Search,
  Document,
  Top,
  Calendar,
  View,
  FolderOpened,
  List
} from '@element-plus/icons-vue'
import { projectApi, announcementApi } from '@/api/project'
import { useTeamStore } from '@/stores/teamStore'
import type { Project, Announcement, AnnouncementStatistics } from '@/types/project'
import AnnouncementCard from './AnnouncementCard.vue'
import CreateAnnouncementDialog from './CreateAnnouncementDialog.vue'
import EditAnnouncementDialog from './EditAnnouncementDialog.vue'

// Props
interface Props {
  teamId: number
  canManage: boolean
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  announcementUpdated: []
}>()

const { t } = useI18n()
const teamStore = useTeamStore()

// 响应式数据
const loading = ref(false)
const projects = ref<Project[]>([])
const announcements = ref<Announcement[]>([])
const announcementStats = ref<AnnouncementStatistics | null>(null)
const selectedProjectId = ref<number | null>(null)
const timeFilter = ref('all')
const searchKeyword = ref('')
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const selectedAnnouncement = ref<Announcement | null>(null)

// 分页数据
const pagination = ref({
  page: 1,
  size: 20,
  total: 0
})

// 计算属性
const teamMembers = computed(() => {
  return teamStore.teamMembers.filter(member => member.status === 'ACTIVE')
})

const timeFilterOptions = computed(() => [
  { value: 'all', label: t('project.allTime') },
  { value: 'today', label: t('project.today') },
  { value: 'week', label: t('project.thisWeek') },
  { value: 'month', label: t('project.thisMonth') }
])

const pinnedAnnouncements = computed(() => {
  return announcements.value.filter(a => a.isPinned)
})

const regularAnnouncements = computed(() => {
  return announcements.value.filter(a => !a.isPinned)
})

// 方法
const fetchProjects = async () => {
  try {
    const response = await projectApi.getTeamProjects(props.teamId)

    if (response.code !== 200) {
      throw new Error(response.message || '获取项目列表失败')
    }

    projects.value = response.data || []

    // 如果有项目且没有选中项目，默认选中第一个
    if (projects.value.length > 0 && !selectedProjectId.value) {
      selectedProjectId.value = projects.value[0].id
      await fetchAnnouncements()
      await fetchAnnouncementStats()
    }
  } catch (error: any) {
    console.error('获取项目列表失败:', error)
    ElMessage.error(error.message || t('project.fetchError'))
  }
}

const fetchAnnouncements = async () => {
  if (!selectedProjectId.value) return

  try {
    loading.value = true

    // 获取置顶公告
    const pinnedResponse = await announcementApi.getProjectAnnouncements(selectedProjectId.value, true)

    if (pinnedResponse.code !== 200) {
      throw new Error(pinnedResponse.message || '获取置顶公告失败')
    }

    const pinnedData = pinnedResponse.data || []

    let regularData: Announcement[] = []

    if (searchKeyword.value) {
      // 搜索公告
      const searchResponse = await announcementApi.searchAnnouncements(selectedProjectId.value, searchKeyword.value)

      if (searchResponse.code !== 200) {
        throw new Error(searchResponse.message || '搜索公告失败')
      }

      regularData = (searchResponse.data || []).filter(a => !a.isPinned)
      pagination.value.total = regularData.length
    } else if (timeFilter.value !== 'all') {
      // 按时间筛选
      let timeResponse
      switch (timeFilter.value) {
        case 'today':
          timeResponse = await announcementApi.getTodayAnnouncements(selectedProjectId.value)
          break
        case 'week':
          timeResponse = await announcementApi.getWeekAnnouncements(selectedProjectId.value)
          break
        case 'month':
          timeResponse = await announcementApi.getMonthAnnouncements(selectedProjectId.value)
          break
      }

      if (timeResponse && timeResponse.code !== 200) {
        throw new Error(timeResponse.message || '获取时间筛选公告失败')
      }

      regularData = (timeResponse?.data || []).filter(a => !a.isPinned)
      pagination.value.total = regularData.length
    } else {
      // 分页获取非置顶公告
      const regularResponse = await announcementApi.getProjectAnnouncementsPage(
        selectedProjectId.value,
        {
          page: pagination.value.page - 1, // 后端从0开始
          size: pagination.value.size
        },
        true // 排除置顶公告
      )

      if (regularResponse.code !== 200) {
        throw new Error(regularResponse.message || '获取公告列表失败')
      }

      regularData = regularResponse.data?.content || []
      pagination.value.total = regularResponse.data?.totalElements || 0
    }

    // 合并置顶和普通公告
    announcements.value = [...pinnedData, ...regularData]
  } catch (error: any) {
    console.error('获取公告列表失败:', error)
    ElMessage.error(error.message || t('project.fetchAnnouncementsError'))
  } finally {
    loading.value = false
  }
}

const fetchAnnouncementStats = async () => {
  if (!selectedProjectId.value) return

  try {
    const response = await announcementApi.getAnnouncementStatistics(selectedProjectId.value)

    if (response.code !== 200) {
      throw new Error(response.message || '获取公告统计失败')
    }

    announcementStats.value = response.data
  } catch (error: any) {
    console.error('获取公告统计失败:', error)
    // 统计失败不显示错误消息，只在控制台记录
  }
}

const handleProjectChange = async () => {
  pagination.value.page = 1
  timeFilter.value = 'all'
  searchKeyword.value = ''
  await fetchAnnouncements()
  await fetchAnnouncementStats()
}

const handleTimeFilterChange = async () => {
  pagination.value.page = 1
  searchKeyword.value = ''
  await fetchAnnouncements()
}

const handleSearch = async () => {
  pagination.value.page = 1
  timeFilter.value = 'all'
  await fetchAnnouncements()
}

const handleSizeChange = async (size: number) => {
  pagination.value.size = size
  pagination.value.page = 1
  await fetchAnnouncements()
}

const handleCurrentChange = async (page: number) => {
  pagination.value.page = page
  await fetchAnnouncements()
}

const handleCreateSuccess = () => {
  showCreateDialog.value = false
  fetchAnnouncements()
  fetchAnnouncementStats()
  emit('announcementUpdated')
}

const handleEditAnnouncement = (announcement: Announcement) => {
  selectedAnnouncement.value = announcement
  showEditDialog.value = true
}

const handleEditSuccess = () => {
  showEditDialog.value = false
  selectedAnnouncement.value = null
  fetchAnnouncements()
  fetchAnnouncementStats()
  emit('announcementUpdated')
}

const handleDeleteAnnouncement = async (announcement: Announcement) => {
  try {
    await ElMessageBox.confirm(
      t('project.deleteAnnouncementConfirmMessage', { title: announcement.title }),
      t('project.deleteAnnouncementConfirmTitle'),
      {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      }
    )

    await announcementApi.deleteAnnouncement(announcement.id)
    ElMessage.success(t('project.deleteAnnouncementSuccess'))
    fetchAnnouncements()
    fetchAnnouncementStats()
    emit('announcementUpdated')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除公告失败:', error)
      ElMessage.error(t('project.deleteAnnouncementError'))
    }
  }
}

const handlePinAnnouncement = async (announcement: Announcement) => {
  try {
    await announcementApi.pinAnnouncement(announcement.id)
    announcement.isPinned = true
    ElMessage.success(t('project.pinAnnouncementSuccess'))
    fetchAnnouncements()
    fetchAnnouncementStats()
    emit('announcementUpdated')
  } catch (error) {
    console.error('置顶公告失败:', error)
    ElMessage.error(t('project.pinAnnouncementError'))
  }
}

const handleUnpinAnnouncement = async (announcement: Announcement) => {
  try {
    await announcementApi.unpinAnnouncement(announcement.id)
    announcement.isPinned = false
    ElMessage.success(t('project.unpinAnnouncementSuccess'))
    fetchAnnouncements()
    fetchAnnouncementStats()
    emit('announcementUpdated')
  } catch (error) {
    console.error('取消置顶公告失败:', error)
    ElMessage.error(t('project.unpinAnnouncementError'))
  }
}

// 生命周期
onMounted(() => {
  fetchProjects()
  
  // 加载团队成员
  if (teamStore.teamMembers.length === 0) {
    teamStore.fetchTeamMembers(props.teamId)
  }
})

// 监听teamId变化
watch(() => props.teamId, () => {
  if (props.teamId) {
    fetchProjects()
  }
})
</script>

<style scoped lang="scss">
.announcement-system {
  .announcement-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;
    gap: 24px;

    .toolbar-left {
      flex: 1;

      .announcement-title {
        margin: 0 0 16px 0;
        font-size: 20px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }

      .announcement-filters {
        display: flex;
        gap: 12px;
        flex-wrap: wrap;

        .project-select {
          min-width: 200px;
        }

        .time-select {
          min-width: 150px;
        }
      }
    }

    .toolbar-right {
      display: flex;
      gap: 12px;
      align-items: center;

      .search-input {
        width: 250px;
      }
    }
  }

  .announcement-stats {
    margin-bottom: 24px;

    .stat-card {
      position: relative;
      overflow: hidden;

      .stat-content {
        .stat-value {
          font-size: 24px;
          font-weight: 600;
          color: var(--el-text-color-primary);
          margin-bottom: 4px;
        }

        .stat-label {
          font-size: 14px;
          color: var(--el-text-color-secondary);
        }
      }

      .stat-icon {
        position: absolute;
        right: 16px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 32px;
        opacity: 0.3;

        &.total {
          color: var(--el-color-info);
        }
      }

      &.pinned .stat-icon {
        color: var(--el-color-danger);
      }

      &.today .stat-icon {
        color: var(--el-color-success);
      }

      &.week .stat-icon {
        color: var(--el-color-primary);
      }
    }
  }

  .announcement-list-container {
    .empty-state,
    .empty-announcements {
      text-align: center;
      padding: 40px;
    }

    .announcement-list {
      .section-title {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 16px;
        font-size: 16px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }

      .pinned-announcements {
        margin-bottom: 32px;
      }

      .regular-announcements {
        margin-bottom: 24px;
      }
    }

    .pagination-container {
      margin-top: 24px;
      display: flex;
      justify-content: center;
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .announcement-system {
    .announcement-toolbar {
      flex-direction: column;
      align-items: stretch;

      .toolbar-left {
        .announcement-filters {
          .project-select,
          .time-select {
            min-width: 120px;
          }
        }
      }

      .toolbar-right {
        justify-content: flex-end;

        .search-input {
          width: 200px;
        }
      }
    }

    .announcement-stats {
      .el-row {
        .el-col {
          margin-bottom: 16px;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .announcement-system {
    .announcement-toolbar {
      .toolbar-left {
        .announcement-filters {
          flex-direction: column;

          .project-select,
          .time-select {
            width: 100%;
          }
        }
      }

      .toolbar-right {
        flex-direction: column;
        align-items: stretch;

        .search-input {
          width: 100%;
        }
      }
    }
  }
}
</style>
